<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { omit } from 'lodash-es'
import { indexConfig } from './config'
import PageFormTable from '@/components/page/BaseFormTable/index.vue'
import { createUser, disableUser, getAllUsers, sendRegisterCaptcha, sendUpdateInfoCaptcha, updateUser } from '@/api/user'
import { useFetch } from '@/composables/useFetch'
import { getRole } from '@/api/role'

const PageFormTableRef = ref<InstanceType<typeof PageFormTable>>()
const disabledEditOptions = ['password']
const apiConfig = {
  getTableList: getAllUsers,
  addTableItem: createUser,
  updateTableItem: updateUser,
  deleteTableItem: disableUser,
  _handleEditModel,
}

// 页面请求
const { data: listResult, execute: getListExecute } = useFetch((parmas: any) => getAllUsers(parmas))
const { data: captchaData, execute: getUpdateInfoCaptchaExecute } = useFetch((parmas: any) => sendUpdateInfoCaptcha(parmas))
const { data: registerCaptchaData, execute: getRegisterCaptchaExecute } = useFetch((parmas: any) => sendRegisterCaptcha(parmas))
const { data: roleResult, execute: getRoleListExecute } = useFetch((parmas: any) => getRole(parmas))

// 顶部搜索初始化
onMounted(() => {
  _handleInitSearchForm()
  _handleInitModalForm()
})
const searchFormOptions = ref(indexConfig.searchFormOptions)
const initIndexConfig = ref(indexConfig)
async function _handleInitSearchForm() {
  await getListExecute({ pageSize: 1000 })
  const tableList = listResult.value!.data || []
  const children = tableList.map((item: any) => {
    return {
      type: 'select-option',
      label: item.username,
      value: item.username,
    }
  })
  searchFormOptions.value = indexConfig.searchFormOptions.map((item: any) => {
    if (item.prop === 'username') {
      return {
        ...item,
        children,
      }
    }
    return item
  })
}

async function _handleInitModalForm() {
  await getRoleListExecute()

  const roleChildren = roleResult.value!.data.map((item: any) => {
    return {
      type: 'checkbox',
      label: item.name,
      value: item.name,
    }
  })

  searchFormOptions.value = indexConfig.searchFormOptions.map((item: any) => {
    if (item.prop === 'roles') {
      return {
        ...item,
        children: roleChildren,
      }
    }
    return item
  })

  initIndexConfig.value.options = indexConfig.options.map((item: any) => {
    if (item.prop === 'roles') {
      return {
        ...item,
        children: roleChildren,
      }
    }
    return item
  })
}

function _handleEditModel(data: any) {
  const editData = omit(data, ['createTime', 'updateTime'])
  return {
    ...editData,
    isFrozen: editData.isFrozen ? '1' : '0',
  }
}

async function onClickSendCode(record: any) {
  if (record.type === 'add') {
    await getRegisterCaptchaExecute({ address: record.data.email })
    if (registerCaptchaData.value!.code === 200)
      window.$message.success(registerCaptchaData.value!.data as string || 'send success!')
  }
  if (record.type === 'edit') {
    await getUpdateInfoCaptchaExecute({ address: record.data.email })
    if (captchaData.value!.code === 200)
      window.$message.success(captchaData.value!.data as string || 'send success!')
  }
}
</script>

<template>
  <PageFormTable
    ref="PageFormTableRef"
    :search-form-options="searchFormOptions"
    :config="initIndexConfig"
    :api-config="apiConfig"
    :disabled-edit-options="disabledEditOptions"
  >
    <template #customs="{ column, record }">
      <template v-if="column.dataIndex === 'action'">
        <div class="gp__flex-start">
          <a-button class="gp__second-btn" @click="PageFormTableRef?.onClickEditForm({ ...record })">
            {{ indexConfig.text.editAction }}
          </a-button>
          <a-popconfirm
            :title="record.isFrozen ? indexConfig.text.confirmEnableInfo : indexConfig.text.confirmDisableInfo"
            :cancel-text="indexConfig.text.popNoText"
          >
            <template #okButton>
              <a-button type="primary" size="small" :loading="PageFormTableRef?.deleteLoading" @click="PageFormTableRef?.onClickDeleteAction({ id: record.id })">
                {{ indexConfig.text.popOkText }}
              </a-button>
            </template>
            <a-button :danger="!record.isFrozen">
              {{ record.isFrozen ? indexConfig.text.enableAction : indexConfig.text.disableAction }}
            </a-button>
          </a-popconfirm>
        </div>
      </template>
    </template>
    <template #FormFooter="record">
      <a-button class="gp__second-btn" style="position: absolute; right: 40px;" @click="onClickSendCode(record)">
        发送验证码
      </a-button>
    </template>
  </PageFormTable>
</template>
